package com.xjy.rpc.netty.handler.listener;

import com.xjy.rpc.netty.client.Client;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * @description: 客户端短线重连后的监听器
 * @author XJY
 * @date 2024/10/17 13:46
 * @version 1.0
 */
@Slf4j
public class ReConnectListener implements ChannelFutureListener {
    //重试x次后还重连不上直接抛出异常
    private static final AtomicInteger count = new AtomicInteger(0);

    private Client client;

    public ReConnectListener(Client client){
        this.client = client;
    }
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
        if (!future.isSuccess()){
            log.info("{}:{}服务连接失败，开始断线重连...",client.getIp(),client.getPort());
            final EventLoop eventLoop = future.channel().eventLoop();
            eventLoop.schedule(()->{
                try{
                    //TODO 这个10和3后续可优化为配置
                    while (count.getAndIncrement() < 10){
                        log.info("第{}次重连开始",count.get());
                        client.connect();
                    }
                    log.info("失败重连尝试次数达最次数{}，断开连接",(count.get() - 1));
                    client.shutdown();
                } catch (Exception e){
                    log.info("连接失败...");
                }
            },3, TimeUnit.SECONDS);
        } else {
            log.info("{}:{}连接成功",client.getIp(),client.getPort());
            count.set(0);
        }
    }
}
